package com.talent.jiwen_teacher;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.talent.jiwen_teacher.base.BaseActivity;

import butterknife.BindView;

/**
 * Created by qyqx on 2018/7/20.
 */

public class SelectFileActivity extends BaseActivity {

    @BindView(R.id.select_web)
    WebView h5WebView;

//    @BindView(R.id.bt_pdf)
//    Button bt_pdf;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_select_file;
    }

    @Override
    public String titleName() {
        return null;
    }

    @Override
    protected void initData() {

        initWeb();
    }

//    @SuppressLint("JavascriptInterface")
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_select_file);
//        h5WebView=findView(R.id.select_web);
//        bt_pdf=findView(R.id.bt_pdf);
//        bt_pdf.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        initWeb();
//        h5WebView.loadUrl("http://192.168.10.112:8080/test/testEDU?token=222&roomId=123asdzxc");//加载url

        //使用webview显示html代码
//        webView.loadDataWithBaseURL(null,"<html><head><title> 欢迎您 </title></head>" +
//                "<body><h2>使用webview显示 html代码</h2></body></html>", "text/html" , "utf-8", null);

//        webView.addJavascriptInterface(this,"android");//添加js监听 这样html就能调用客户端
////        webView.setWebChromeClient(webChromeClient);
////        webView.setWebViewClient(webViewClient);
//        webView.setWebChromeClient(new MyWebChomeClient(new OpenFileChooserCallBack() {
//            @Override
//            public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
//                showOptions();
//            }
//
//            @Override
//            public void openFileChooser5CallBack(WebView webView, ValueCallback<Uri[]> valueCallback, WebChromeClient.FileChooserParams fileChooserParams) {
//                showOptions();
//            }
//        }));
//        WebSettings webSettings=webView.getSettings();
//        webSettings.setJavaScriptEnabled(true);//允许使用js

        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
//
//        //支持屏幕缩放
//        webSettings.setSupportZoom(true);
//        webSettings.setBuiltInZoomControls(true);

        //不显示webview缩放按钮
//        webSettings.setDisplayZoomControls(false);
//
//    }
    private String webUrl = "http://192.168.10.112:8080/test/testEDU?token=222&roomId=123asdzxc";

    public ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public ValueCallback<Uri> mUploadMessage;
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    private final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调
    private Uri imageUri;


    // 初始化webview
    @SuppressLint("SetJavaScriptEnabled")
    private void initWeb() {

        WebSettings mWebSettings = h5WebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true); //允许加载javaScript
        mWebSettings.setSupportZoom(true);       //是否允许缩放
        mWebSettings.setUseWideViewPort(true);   //设置加载进来的页面自适应手机屏幕
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);


        h5WebView.canGoBack();
        h5WebView.loadUrl(webUrl);

        //H5加载链接监听
//        h5WebView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                Intent intent = null;
//                //根据拦截的url来判断是否拦截跳转
//                if (url.contains("test")) {
//                    intent = new Intent(SelectFileActivity.this, Test.class);
//                } else if (url.contains("returnBackController")) {
////                    ...
//                }else if (url.contains("....")) {
//                    h5WebView.loadUrl("javascript:reload()");
//                }else {
//                    h5WebView.loadUrl(webUrl);
//                }
//                if (intent != null){
//                    startActivity(intent);
//                }
//                return true;
//            }
//
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//            }
//
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//            }
//        });


        //H5界面加载进度监听
        h5WebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {

//                if (webProgressBar != null){
//                    if (newProgress > 95){
//                        webProgressBar.setVisibility(View.GONE);
//                    }else if (newProgress < 95 && webProgressBar.getVisibility() == View.GONE){
//                        webProgressBar.setVisibility(View.VISIBLE);
//                    }
//                    webProgressBar.setProgress(newProgress);
//                }
                super.onProgressChanged(view, newProgress);
            }

            // For Android < 5.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            // For Android => 5.0
            public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> uploadMsg,
                                              WebChromeClient.FileChooserParams fileChooserParams) {
                onenFileChooseImpleForAndroid(uploadMsg);
                return true;
            }

        });


//        h5WebView.setWebViewClient(new WebViewClient(){
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
//            }
//        });





        /**
         * 监听手机返回按键，点击返回H5就返回上一级
         */
        h5WebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && h5WebView.canGoBack()) {
                    h5WebView.goBack();
                    return true;
                }
                return false;
            }
        });
    }



    /**
     * android 5.0 以下开启图片选择（原生）
     *
     * 可以自己改图片选择框架。
     */
    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");
        i.setType(".ppt,.pdf");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_CHOOSER_RESULT_CODE);
    }


    /**
     * android 5.0(含) 以上开启图片选择（原生）
     *
     * 可以自己改图片选择框架。
     */
    private void onenFileChooseImpleForAndroid(ValueCallback<Uri[]> filePathCallback) {
        mUploadMessageForAndroid5 = filePathCallback;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
//        contentSelectionIntent.setType("image/*");
        contentSelectionIntent.setType("ppt/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode,Intent intent) {
        Uri result = (intent == null || resultCode != Activity.RESULT_OK) ? null: intent.getData();
        switch (requestCode){
            case FILE_CHOOSER_RESULT_CODE:  //android 5.0以下 选择图片回调

                if (null == mUploadMessage)
                    return;
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;

                break;

            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:  //android 5.0(含) 以上 选择图片回调

                if (null == mUploadMessageForAndroid5)
                    return;
                if (result != null) {
                    mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
                } else {
                    mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
                }
                mUploadMessageForAndroid5 = null;

                break;
        }
    }




//    private static final int REQUEST_CODE_PICK_IMAGE = 0;
//    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
//    private Intent mSourceIntent;
//    //针对5.0以下版本
//    private ValueCallback<Uri> mUploadMsg;
//    //这对5.0以上版本
//    private ValueCallback<Uri[]> mValueCallback;


//    @Override
//    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
//        mUploadMsg = uploadMsg;
////        showOptions();
//
//    }
//
//    @Override
//    public void openFileChooser5CallBack(WebView webView, ValueCallback<Uri[]> valueCallback, WebChromeClient.FileChooserParams fileChooserParams) {
//        mValueCallback = valueCallback;
////        showOptions();
//    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == RESULT_CANCELED) {
//            if (mUploadMsg != null) {
//                mUploadMsg.onReceiveValue(null);
//                mUploadMsg = null;
//            }
//            if (mValueCallback != null) {
//                mValueCallback.onReceiveValue(null);
//                mValueCallback = null;
//            }
//        }
//        switch (requestCode) {
//            case REQUEST_CODE_IMAGE_CAPTURE:
//            case REQUEST_CODE_PICK_IMAGE: {
//                try {
//                    if (mUploadMsg != null) {
//
//                    } else if (mValueCallback != null) {
//
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                break;
//            }
//        }
//    }
//
//    String [] options=new String[]{"取消","确定"};
//
//    public void showOptions() {
//        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
//        alertDialog.setOnCancelListener(new ReOnCancelListener());
//        alertDialog.setTitle("选择");
//        alertDialog.setItems(options, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (which == 0) {
////                            mSourceIntent = ImageUtil.choosePicture();
//                            startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
//                        } else {
////                            mSourceIntent = ImageUtil.takeBigPicture();
//                            startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
//                        }
//                    }
//                }
//
//        );
//        alertDialog.show();
//    }
//
//    //这个必须要写，要不然第一次取消选择文件后第二次就调用不了选择文件这个功能了，所以一定要写
//    private class ReOnCancelListener implements DialogInterface.OnCancelListener {
//
//        @Override
//        public void onCancel(DialogInterface dialogInterface) {
//            if (mUploadMsg != null) {
//                mUploadMsg.onReceiveValue(null);
//                mUploadMsg = null;
//            }
//            if (mValueCallback != null) {
//                mValueCallback.onReceiveValue(null);
//                mValueCallback = null;
//            }
//        }
//    }

//    private WebViewClient webViewClient=new WebViewClient(){
//        @Override
//        public void onPageFinished(WebView view, String url) {//页面加载完成
////            progressBar.setVisibility(View.GONE);
//        }
//
//        @Override
//        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
////            progressBar.setVisibility(View.VISIBLE);
//        }
//
//        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            Log.i("ansen","拦截url:"+url);
//            if(url.equals("http://www.google.com/")){
////                Toast.makeText(MainActivity.this,"国内不能访问google,拦截该url",Toast.LENGTH_LONG).show();
//                return true;//表示我已经处理过了
//            }
//            return super.shouldOverrideUrlLoading(view, url);
//        }
//
//    };


    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
//    private WebChromeClient webChromeClient=new WebChromeClient(){
//        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
//        @Override
//        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
//            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
//            localBuilder.setMessage(message).setPositiveButton("确定",null);
//            localBuilder.setCancelable(false);
//            localBuilder.create().show();
//
//            //注意:
//            //必须要这一句代码:result.confirm()表示:
//            //处理结果为确定状态同时唤醒WebCore线程
//            //否则不能继续点击按钮
//            result.confirm();
//            return true;
//        }
//
//        //获取网页标题
//        @Override
//        public void onReceivedTitle(WebView view, String title) {
//            super.onReceivedTitle(view, title);
//            Log.i("ansen","网页标题:"+title);
//        }
//
//        //加载进度回调
//        @Override
//        public void onProgressChanged(WebView view, int newProgress) {
////            progressBar.setProgress(newProgress);
//        }
//    };

    public class MyWebChomeClient extends WebChromeClient {

        private OpenFileChooserCallBack mOpenFileChooserCallBack;

        public MyWebChomeClient(OpenFileChooserCallBack openFileChooserCallBack) {
            mOpenFileChooserCallBack = openFileChooserCallBack;
        }

        //针对 Android 5.0+
//        @Override
//        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback,
//                                         android.webkit.WebChromeClient.FileChooserParams fileChooserParams) {
//            mOpenFileChooserCallBack.openFileChooser5CallBack(webView, valueCallback, fileChooserParams);
//            return true;
//
//        }


        //针对 Android版本 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mOpenFileChooserCallBack.openFileChooserCallBack(uploadMsg, acceptType);
        }

        // 针对 Android版本 < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        //针对 Android版本  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }



        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            //  return super.onJsAlert(view, url, message, result);
            return true;
        }
    }

    //回调的接口
    public interface OpenFileChooserCallBack {
        void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType);

        void openFileChooser5CallBack(WebView webView, ValueCallback<Uri[]> valueCallback,
                                      android.webkit.WebChromeClient.FileChooserParams fileChooserParams);
    }

        @Override
    protected void onDestroy() {
        super.onDestroy();

        //释放资源
            h5WebView.destroy();
            h5WebView=null;
    }

}
